from django.shortcuts import get_object_or_404, HttpResponseRedirect
from django.views.generic import list_detail
from django.http import Http404
from readers.models import *

def msg_check(request):
	''' 
	Check reserving and giving-up messages
	'''
	try:
		i = int(request.GET.get('i', '0'))
		o = int(request.GET.get('o', '0'))
		
		if i:
			reserving = get_object_or_404(Reserving, pk=i)
			Reading.objects.get_or_create(user_reading=reserving.user_reserving,
				book_read=reserving.book_reserved, status="C")
			reserving.status = 'A'
			reserving.save()

			return HttpResponseRedirect('/msgs/')
		if o:
			reading = get_object_or_404(Reading, pk=o)
			reading.status = 'A'
			reading.save()

			return HttpResponseRedirect('/msgs/')
	except:
		raise Http404

	return list_detail.object_list(
		request,
		queryset = Reserving.objects.filter(status='C'),
		template_name = 'msgs/msg_check.html',
		# template_object_name = 'reservings',
		extra_context = { 'giving_backs_list': Reading.objects.filter(status='B') }
	)
